﻿using AutoMapper;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using ZeroSum.Helpers;

namespace ZeroSum.Extend.Mapper;

/// <summary>
///     AutoMapper扩展
/// </summary>
public static class MapperExtensions
{
    /// <summary>
    ///     注册AutoMapper，并扫描所有需要自动注册的关系
    ///     会自动注册ITypeConvert的实现并创建Mapping
    /// </summary>
    /// <param name="services"></param>
    /// <returns></returns>
    public static IServiceCollection AddAutoMapper(this IServiceCollection services)
    {
        var assemblies = AssemblyHelper.GetProjectAssemblies().ToList();

        // 扫描预置的Profile
        assemblies.Add(typeof(MapperExtensions).Assembly);

        services.AddAutoMapper(assemblies);
        return services;
    }

    public static IApplicationBuilder UseAutoMapper(this IApplicationBuilder app)
    {
        var provider = app.ApplicationServices;
        var mapper = provider.GetService<IMapper>()!;
        Extensions.MapperExtensions.SetMapper(mapper);
        return app;
    }
}